<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>移除背景</title>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3a0ca3;
            --success-color: #4cc9f0;
            --warning-color: #f72585;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --gray-color: #6c757d;
            --border-radius: 8px;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--dark-color);
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 25px;
            text-align: center;
            position: relative;
        }
        
        .home-btn {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
            text-decoration: none;
        }
        
        .home-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 700px;
            margin: 0 auto;
        }
        
        .main-content {
            display: flex;
            flex-wrap: wrap;
            padding: 25px;
            gap: 25px;
        }
        
        .upload-section {
            flex: 1;
            min-width: 300px;
        }
        
        .preview-section {
            flex: 2;
            min-width: 300px;
        }
        
        .section-title {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: var(--primary-color);
            padding-bottom: 8px;
            border-bottom: 2px solid #e0e0e0;
        }
        
        .upload-box {
            border: 2px dashed var(--primary-color);
            border-radius: var(--border-radius);
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            background-color: var(--light-color);
            position: relative;
        }
        
        .upload-box:hover, .upload-box.dragover {
            background-color: #e9ecef;
            border-color: var(--secondary-color);
        }
        
        .upload-icon {
            font-size: 3.5rem;
            color: var(--primary-color);
            margin-bottom: 15px;
        }
        
        .upload-text {
            margin-bottom: 20px;
            font-size: 1.1rem;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            transition: var(--transition);
            font-weight: 500;
        }
        
        .btn:hover {
            background: var(--secondary-color);
            transform: translateY(-2px);
        }
        
        .btn:disabled {
            background: var(--gray-color);
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-success {
            background: var(--success-color);
        }
        
        .btn-success:hover {
            background: #3a9fc7;
        }
        
        #file-input {
            display: none;
        }
        
        .controls {
            margin-top: 20px;
            padding: 20px;
            background: var(--light-color);
            border-radius: var(--border-radius);
        }
        
        .control-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        input[type="range"] {
            width: 100%;
            height: 8px;
            -webkit-appearance: none;
            appearance: none;
            background: #ddd;
            border-radius: 4px;
            outline: none;
        }
        
        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: var(--primary-color);
            cursor: pointer;
        }
        
        input[type="number"], select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 1rem;
            width: 100%;
            margin-bottom: 8px;
        }
        
        .range-value {
            display: inline-block;
            width: 40px;
            text-align: right;
            font-weight: bold;
            color: var(--primary-color);
        }
        
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .preview-box {
            flex: 1;
            min-width: 250px;
        }
        
        .preview-title {
            text-align: center;
            margin-bottom: 10px;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .canvas-container {
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            overflow: hidden;
            background-image: 
                linear-gradient(45deg, #f0f0f0 25%, transparent 25%), 
                linear-gradient(-45deg, #f0f0f0 25%, transparent 25%),
                linear-gradient(45deg, transparent 75%, #f0f0f0 75%),
                linear-gradient(-45deg, transparent 75%, #f0f0f0 75%);
            background-size: 20px 20px;
            background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
        }
        
        canvas {
            display: block;
            max-width: 100%;
            margin: 0 auto;
        }
        
        .download-btn {
            display: block;
            width: 100%;
            margin-top: 20px;
            padding: 15px;
            background: var(--success-color);
            text-align: center;
            color: white;
            text-decoration: none;
            border-radius: var(--border-radius);
            font-weight: 600;
            transition: var(--transition);
        }
        
        .download-btn:hover {
            background: #3a9fc7;
            transform: translateY(-2px);
        }
        
        .progress-container {
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            margin: 15px 0;
            overflow: hidden;
            display: none;
        }
        
        .progress-bar {
            height: 100%;
            background-color: var(--primary-color);
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .status {
            margin-top: 10px;
            font-style: italic;
            color: var(--primary-color);
            text-align: center;
            min-height: 24px;
        }
        
        .tips {
            margin-top: 25px;
            padding: 15px;
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            border-radius: 4px;
        }
        
        .tips-title {
            font-weight: bold;
            margin-bottom: 8px;
            color: #856404;
        }
        
        .tips-list {
            padding-left: 20px;
        }
        
        .tips-list li {
            margin-bottom: 5px;
        }
        
        footer {
            text-align: center;
            padding: 20px;
            color: var(--gray-color);
            font-size: 0.9rem;
            border-top: 1px solid #e9ecef;
        }
        
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .preview-container {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <a href="index.html" class="home-btn">返回首页</a>
            <h1>移除背景</h1>
            <p class="description">上传图片，智能去除背景，特别适合图标和小图片。完全在浏览器中处理，保护您的隐私。</p>
        </header>
        
        <div class="main-content">
            <div class="upload-section">
                <h2 class="section-title">上传图片</h2>
                <div class="upload-box" id="upload-area">
                    <div class="upload-icon">📁</div>
                    <p class="upload-text">点击或拖放图片到此处</p>
                    <button class="btn">选择图片</button>
                    <input type="file" id="file-input" accept="image/*">
                </div>
                
                <div class="controls">
                    <div class="control-group">
                        <label for="method-select">背景去除方法:</label>
                        <select id="method-select">
                            <option value="fuzzy">模糊容差法</option>
                            <option value="corner">角落采样法</option>
                            <option value="edge">边缘检测法</option>
                            <option value="advanced">高级算法 (减少残留)</option>
                        </select>
                    </div>
                    
                    <div class="control-group" id="fuzzy-controls">
                        <label for="tolerance-slider">颜色容差: <span id="tolerance-value" class="range-value">50</span></label>
                        <input type="range" id="tolerance-slider" min="0" max="255" value="50">
                    </div>
                    
                    <div class="control-group" id="sample-controls">
                        <label for="sample-x">采样点 X:</label>
                        <input type="number" id="sample-x" min="0" value="0">
                        
                        <label for="sample-y">采样点 Y:</label>
                        <input type="number" id="sample-y" min="0" value="0">
                    </div>
                    
                    <div class="control-group" id="advanced-controls" style="display: none;">
                        <label for="edge-refinement">边缘优化强度: <span id="edge-refinement-value" class="range-value">5</span></label>
                        <input type="range" id="edge-refinement" min="1" max="10" value="5">
                        
                        <label for="residual-removal">残留去除强度: <span id="residual-removal-value" class="range-value">3</span></label>
                        <input type="range" id="residual-removal" min="1" max="10" value="3">
                    </div>
                    
                    <div class="progress-container" id="progress-container">
                        <div class="progress-bar" id="progress-bar"></div>
                    </div>
                    
                    <button id="process-btn" class="btn" disabled>去除背景</button>
                    
                    <div class="status" id="status"></div>
                </div>
                
                <div class="tips">
                    <p class="tips-title">使用提示：</p>
                    <ul class="tips-list">
                        <li>纯色背景图片效果最佳</li>
                        <li>对于复杂背景，尝试调整容差和采样点</li>
                        <li>角落采样法适合背景颜色均匀的图片</li>
                        <li>边缘检测法适合主体与背景对比明显的图片</li>
                        <li>高级算法专门优化减少背景残留</li>
                        <li>处理后右键点击图片可保存为PNG格式</li>
                    </ul>
                </div>
            </div>
            
            <div class="preview-section">
                <h2 class="section-title">预览结果</h2>
                <div class="preview-container">
                    <div class="preview-box">
                        <p class="preview-title">原始图片</p>
                        <div class="canvas-container">
                            <canvas id="original-canvas"></canvas>
                        </div>
                    </div>
                    <div class="preview-box">
                        <p class="preview-title">处理后图片</p>
                        <div class="canvas-container">
                            <canvas id="result-canvas"></canvas>
                        </div>
                    </div>
                </div>
                
                <a id="download-btn" class="download-btn" href="#" download="transparent-image.png" style="display: none;">
                    📥 下载透明背景图片
                </a>
            </div>
        </div>
        
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const fileInput = document.getElementById('file-input');
            const uploadArea = document.getElementById('upload-area');
            const processBtn = document.getElementById('process-btn');
            const downloadBtn = document.getElementById('download-btn');
            const originalCanvas = document.getElementById('original-canvas');
            const resultCanvas = document.getElementById('result-canvas');
            const toleranceSlider = document.getElementById('tolerance-slider');
            const toleranceValue = document.getElementById('tolerance-value');
            const sampleXInput = document.getElementById('sample-x');
            const sampleYInput = document.getElementById('sample-y');
            const methodSelect = document.getElementById('method-select');
            const statusDiv = document.getElementById('status');
            const progressContainer = document.getElementById('progress-container');
            const progressBar = document.getElementById('progress-bar');
            const edgeRefinementSlider = document.getElementById('edge-refinement');
            const edgeRefinementValue = document.getElementById('edge-refinement-value');
            const residualRemovalSlider = document.getElementById('residual-removal');
            const residualRemovalValue = document.getElementById('residual-removal-value');
            const advancedControls = document.getElementById('advanced-controls');
            
            let originalCtx = originalCanvas.getContext('2d');
            let resultCtx = resultCanvas.getContext('2d');
            let originalImage = null;
            
            // 更新容差值显示
            toleranceSlider.addEventListener('input', function() {
                toleranceValue.textContent = this.value;
            });
            
            // 更新边缘优化值显示
            edgeRefinementSlider.addEventListener('input', function() {
                edgeRefinementValue.textContent = this.value;
            });
            
            // 更新残留去除值显示
            residualRemovalSlider.addEventListener('input', function() {
                residualRemovalValue.textContent = this.value;
            });
            
            // 方法选择变化
            methodSelect.addEventListener('change', function() {
                if (this.value === 'advanced') {
                    advancedControls.style.display = 'block';
                } else {
                    advancedControls.style.display = 'none';
                }
            });
            
            // 点击上传区域触发文件选择
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 拖放功能
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });
            
            uploadArea.addEventListener('dragleave', function() {
                uploadArea.classList.remove('dragover');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                
                if (e.dataTransfer.files.length) {
                    fileInput.files = e.dataTransfer.files;
                    handleFileSelect(e);
                }
            });
            
            // 文件选择处理
            fileInput.addEventListener('change', handleFileSelect);
            
            function handleFileSelect(e) {
                const file = e.target.files[0];
                
                if (!file || !file.type.match('image.*')) {
                    alert('请选择图片文件！');
                    return;
                }
                
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    originalImage = new Image();
                    originalImage.onload = function() {
                        // 调整canvas大小以适应图片
                        const maxWidth = 500;
                        const scale = Math.min(1, maxWidth / originalImage.width);
                        
                        originalCanvas.width = originalImage.width * scale;
                        originalCanvas.height = originalImage.height * scale;
                        
                        resultCanvas.width = originalImage.width * scale;
                        resultCanvas.height = originalImage.height * scale;
                        
                        // 绘制原始图片
                        originalCtx.clearRect(0, 0, originalCanvas.width, originalCanvas.height);
                        originalCtx.drawImage(originalImage, 0, 0, originalCanvas.width, originalCanvas.height);
                        
                        // 设置默认采样点为左上角
                        sampleXInput.value = 0;
                        sampleYInput.value = 0;
                        
                        // 设置采样点最大值为图片尺寸
                        sampleXInput.max = originalCanvas.width - 1;
                        sampleYInput.max = originalCanvas.height - 1;
                        
                        // 启用处理按钮
                        processBtn.disabled = false;
                        
                        // 隐藏下载按钮和状态信息
                        downloadBtn.style.display = 'none';
                        statusDiv.textContent = '点击"去除背景"按钮开始处理';
                    };
                    originalImage.src = e.target.result;
                };
                
                reader.readAsDataURL(file);
            }
            
            // 处理按钮点击事件
            processBtn.addEventListener('click', function() {
                if (!originalImage) return;
                
                // 获取选择的处理方法
                const method = methodSelect.value;
                
                // 显示进度条
                progressContainer.style.display = 'block';
                progressBar.style.width = '0%';
                statusDiv.textContent = '处理中...';
                processBtn.disabled = true;
                
                // 使用setTimeout让UI有机会更新
                setTimeout(function() {
                    try {
                        if (method === 'fuzzy') {
                            removeBackgroundFuzzy();
                        } else if (method === 'corner') {
                            removeBackgroundCorner();
                        } else if (method === 'edge') {
                            removeBackgroundEdge();
                        } else if (method === 'advanced') {
                            removeBackgroundAdvanced();
                        }
                        
                        // 显示下载按钮
                        downloadBtn.style.display = 'block';
                        downloadBtn.href = resultCanvas.toDataURL('image/png');
                        statusDiv.textContent = '处理完成！';
                    } catch (error) {
                        console.error('处理图片时出错:', error);
                        statusDiv.textContent = '处理失败，请重试';
                    } finally {
                        processBtn.disabled = false;
                        progressContainer.style.display = 'none';
                    }
                }, 100);
            });
            
            // 模糊容差法去除背景
            function removeBackgroundFuzzy() {
                // 复制原始图片到结果canvas
                resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
                resultCtx.drawImage(originalImage, 0, 0, resultCanvas.width, resultCanvas.height);
                
                // 获取图像数据
                const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
                const data = imageData.data;
                
                const tolerance = parseInt(toleranceSlider.value);
                let sampleX = parseInt(sampleXInput.value);
                let sampleY = parseInt(sampleYInput.value);
                
                // 边界检查
                sampleX = Math.max(0, Math.min(sampleX, resultCanvas.width - 1));
                sampleY = Math.max(0, Math.min(sampleY, resultCanvas.height - 1));
                
                // 获取采样点颜色
                const baseIndex = (sampleY * resultCanvas.width + sampleX) * 4;
                const baseR = data[baseIndex];
                const baseG = data[baseIndex + 1];
                const baseB = data[baseIndex + 2];
                
                // 处理每个像素
                const totalPixels = data.length / 4;
                for (let i = 0; i < data.length; i += 4) {
                    // 更新进度
                    if (i % 4000 === 0) {
                        progressBar.style.width = `${(i / 4 / totalPixels * 100)}%`;
                    }
                    
                    const r = data[i];
                    const g = data[i + 1];
                    const b = data[i + 2];
                    
                    // 计算颜色差异
                    const diff = Math.abs(r - baseR) + Math.abs(g - baseG) + Math.abs(b - baseB);
                    
                    // 如果颜色相似，设置为透明
                    if (diff <= tolerance) {
                        data[i + 3] = 0; // 设置alpha为0
                    }
                }
                
                // 将处理后的图像数据放回canvas
                resultCtx.putImageData(imageData, 0, 0);
            }
            
            // 角落采样法去除背景
            function removeBackgroundCorner() {
                // 复制原始图片到结果canvas
                resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
                resultCtx.drawImage(originalImage, 0, 0, resultCanvas.width, resultCanvas.height);
                
                // 获取图像数据
                const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
                const data = imageData.data;
                const width = resultCanvas.width;
                const height = resultCanvas.height;
                
                // 收集角落的几个像素作为背景色参考
                const cornerColors = [];
                const sampleSize = Math.max(1, Math.min(width, height) * 0.05); // 取边长的5%作为采样区域
                
                for (let x = 0; x < sampleSize; x++) {
                    for (let y = 0; y < sampleSize; y++) {
                        // 左上角
                        const idx1 = (y * width + x) * 4;
                        cornerColors.push([data[idx1], data[idx1 + 1], data[idx1 + 2]]);
                        
                        // 右上角
                        const idx2 = (y * width + (width - 1 - x)) * 4;
                        cornerColors.push([data[idx2], data[idx2 + 1], data[idx2 + 2]]);
                        
                        // 左下角
                        const idx3 = ((height - 1 - y) * width + x) * 4;
                        cornerColors.push([data[idx3], data[idx3 + 1], data[idx3 + 2]]);
                        
                        // 右下角
                        const idx4 = ((height - 1 - y) * width + (width - 1 - x)) * 4;
                        cornerColors.push([data[idx4], data[idx4 + 1], data[idx4 + 2]]);
                    }
                }
                
                // 计算平均背景色
                let sumR = 0, sumG = 0, sumB = 0;
                cornerColors.forEach(c => {
                    sumR += c[0];
                    sumG += c[1];
                    sumB += c[2];
                });
                
                const count = cornerColors.length;
                const avgR = Math.round(sumR / count);
                const avgG = Math.round(sumG / count);
                const avgB = Math.round(sumB / count);
                
                // 计算背景色的标准差，以确定容差
                let sumDiff = 0;
                cornerColors.forEach(c => {
                    const diff = Math.abs(c[0] - avgR) + Math.abs(c[1] - avgG) + Math.abs(c[2] - avgB);
                    sumDiff += diff;
                });
                
                const avgDiff = sumDiff / count;
                // 动态容差，至少10，最多100，基于平均差异调整
                const tolerance = Math.min(100, Math.max(10, avgDiff * 1.5));
                
                // 处理每个像素
                const totalPixels = data.length / 4;
                for (let i = 0; i < data.length; i += 4) {
                    // 更新进度
                    if (i % 4000 === 0) {
                        progressBar.style.width = `${(i / 4 / totalPixels * 100)}%`;
                    }
                    
                    const r = data[i];
                    const g = data[i + 1];
                    const b = data[i + 2];
                    
                    const diff = Math.abs(r - avgR) + Math.abs(g - avgG) + Math.abs(b - avgB);
                    
                    if (diff <= tolerance) {
                        data[i + 3] = 0; // 设置alpha为0
                    }
                }
                
                // 将处理后的图像数据放回canvas
                resultCtx.putImageData(imageData, 0, 0);
            }
            
            // 边缘检测法去除背景（简化版）
            function removeBackgroundEdge() {
                // 复制原始图片到结果canvas
                resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
                resultCtx.drawImage(originalImage, 0, 0, resultCanvas.width, resultCanvas.height);
                
                // 获取图像数据
                const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
                const data = imageData.data;
                const width = resultCanvas.width;
                const height = resultCanvas.height;
                
                // 简单边缘检测和背景去除
                const tolerance = parseInt(toleranceSlider.value);
                const totalPixels = data.length / 4;
                
                for (let y = 1; y < height - 1; y++) {
                    // 更新进度
                    progressBar.style.width = `${(y / height * 100)}%`;
                    
                    for (let x = 1; x < width - 1; x++) {
                        const idx = (y * width + x) * 4;
                        
                        // 获取周围像素
                        const topIdx = ((y - 1) * width + x) * 4;
                        const bottomIdx = ((y + 1) * width + x) * 4;
                        const leftIdx = (y * width + (x - 1)) * 4;
                        const rightIdx = (y * width + (x + 1)) * 4;
                        
                        // 计算与周围像素的颜色差异
                        let diff = 0;
                        diff += Math.abs(data[idx] - data[topIdx]);
                        diff += Math.abs(data[idx + 1] - data[topIdx + 1]);
                        diff += Math.abs(data[idx + 2] - data[topIdx + 2]);
                        
                        diff += Math.abs(data[idx] - data[bottomIdx]);
                        diff += Math.abs(data[idx + 1] - data[bottomIdx + 1]);
                        diff += Math.abs(data[idx + 2] - data[bottomIdx + 2]);
                        
                        diff += Math.abs(data[idx] - data[leftIdx]);
                        diff += Math.abs(data[idx + 1] - data[leftIdx + 1]);
                        diff += Math.abs(data[idx + 2] - data[leftIdx + 2]);
                        
                        diff += Math.abs(data[idx] - data[rightIdx]);
                        diff += Math.abs(data[idx + 1] - data[rightIdx + 1]);
                        diff += Math.abs(data[idx + 2] - data[rightIdx + 2]);
                        
                        // 如果与周围像素差异小，可能是背景
                        if (diff < tolerance * 4) {
                            data[idx + 3] = 0; // 设置alpha为0
                        }
                    }
                }
                
                // 将处理后的图像数据放回canvas
                resultCtx.putImageData(imageData, 0, 0);
            }
            
            // 高级算法 - 专门减少背景残留
            function removeBackgroundAdvanced() {
                // 复制原始图片到结果canvas
                resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
                resultCtx.drawImage(originalImage, 0, 0, resultCanvas.width, resultCanvas.height);
                
                // 获取图像数据
                const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
                const data = imageData.data;
                const width = resultCanvas.width;
                const height = resultCanvas.height;
                
                // 获取参数
                const edgeRefinement = parseInt(edgeRefinementSlider.value);
                const residualRemoval = parseInt(residualRemovalSlider.value);
                
                // 第一步：使用角落采样法确定背景色
                const cornerColors = [];
                const sampleSize = Math.max(1, Math.min(width, height) * 0.05);
                
                for (let x = 0; x < sampleSize; x++) {
                    for (let y = 0; y < sampleSize; y++) {
                        // 四个角落
                        const idx1 = (y * width + x) * 4;
                        const idx2 = (y * width + (width - 1 - x)) * 4;
                        const idx3 = ((height - 1 - y) * width + x) * 4;
                        const idx4 = ((height - 1 - y) * width + (width - 1 - x)) * 4;
                        
                        cornerColors.push([data[idx1], data[idx1 + 1], data[idx1 + 2]]);
                        cornerColors.push([data[idx2], data[idx2 + 1], data[idx2 + 2]]);
                        cornerColors.push([data[idx3], data[idx3 + 1], data[idx3 + 2]]);
                        cornerColors.push([data[idx4], data[idx4 + 1], data[idx4 + 2]]);
                    }
                }
                
                // 计算平均背景色
                let sumR = 0, sumG = 0, sumB = 0;
                cornerColors.forEach(c => {
                    sumR += c[0];
                    sumG += c[1];
                    sumB += c[2];
                });
                
                const count = cornerColors.length;
                const avgR = Math.round(sumR / count);
                const avgG = Math.round(sumG / count);
                const avgB = Math.round(sumB / count);
                
                // 计算动态容差
                let sumDiff = 0;
                cornerColors.forEach(c => {
                    const diff = Math.abs(c[0] - avgR) + Math.abs(c[1] - avgG) + Math.abs(c[2] - avgB);
                    sumDiff += diff;
                });
                
                const avgDiff = sumDiff / count;
                let tolerance = Math.min(100, Math.max(10, avgDiff * 1.5));
                
                // 第二步：初步去除背景
                const totalPixels = data.length / 4;
                for (let i = 0; i < data.length; i += 4) {
                    // 更新进度
                    if (i % 4000 === 0) {
                        progressBar.style.width = `${(i / 4 / totalPixels * 50)}%`;
                    }
                    
                    const r = data[i];
                    const g = data[i + 1];
                    const b = data[i + 2];
                    
                    const diff = Math.abs(r - avgR) + Math.abs(g - avgG) + Math.abs(b - avgB);
                    
                    if (diff <= tolerance) {
                        data[i + 3] = 0; // 设置alpha为0
                    }
                }
                
                // 第三步：边缘优化和残留去除
                for (let y = 1; y < height - 1; y++) {
                    // 更新进度
                    progressBar.style.width = `${50 + (y / height * 50)}%`;
                    
                    for (let x = 1; x < width - 1; x++) {
                        const idx = (y * width + x) * 4;
                        
                        // 如果当前像素是透明的，检查周围像素
                        if (data[idx + 3] === 0) {
                            let opaqueNeighbors = 0;
                            
                            // 检查8个相邻像素
                            for (let dy = -1; dy <= 1; dy++) {
                                for (let dx = -1; dx <= 1; dx++) {
                                    if (dx === 0 && dy === 0) continue;
                                    
                                    const nIdx = ((y + dy) * width + (x + dx)) * 4;
                                    if (data[nIdx + 3] > 0) {
                                        opaqueNeighbors++;
                                    }
                                }
                            }
                            
                            // 如果周围有很多不透明像素，可能是误判的边缘
                            if (opaqueNeighbors >= edgeRefinement) {
                                data[idx + 3] = 255; // 恢复为不透明
                            }
                        } else {
                            // 对于不透明像素，检查是否可能是残留背景
                            let transparentNeighbors = 0;
                            
                            // 检查8个相邻像素
                            for (let dy = -1; dy <= 1; dy++) {
                                for (let dx = -1; dx <= 1; dx++) {
                                    if (dx === 0 && dy === 0) continue;
                                    
                                    const nIdx = ((y + dy) * width + (x + dx)) * 4;
                                    if (data[nIdx + 3] === 0) {
                                        transparentNeighbors++;
                                    }
                                }
                            }
                            
                            // 如果周围有很多透明像素，检查颜色是否接近背景
                            if (transparentNeighbors >= residualRemoval) {
                                const r = data[idx];
                                const g = data[idx + 1];
                                const b = data[idx + 2];
                                
                                const diff = Math.abs(r - avgR) + Math.abs(g - avgG) + Math.abs(b - avgB);
                                
                                // 使用更严格的容差检查
                                if (diff <= tolerance / 2) {
                                    data[idx + 3] = 0; // 设置为透明
                                }
                            }
                        }
                    }
                }
                
                // 将处理后的图像数据放回canvas
                resultCtx.putImageData(imageData, 0, 0);
            }
        });
    </script>
</body>
</html>